<template>
  <view class="page">
    <!-- 页头导航 -->
    <view class="header-nav">
      <view class="nav-left" @tap="goBack">
        <image
          class="back-icon"
          src="/static/icons/left_arrow.png"
          mode="aspectFit"
        ></image>
      </view>
      <view class="nav-title">编辑公司性质</view>
      <view class="nav-right">
        <text class="save-btn" @tap="handleSubmit" :class="{ disabled: !canSubmit }">保存</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="container">
      <!-- 公司行业 -->
      <view class="form-item">
        <view class="form-label">公司行业</view>
        <view
          class="picker-value"
          @tap="showIndustryPicker = true"
          :class="{ disabled: topIndustryList.length === 0 }"
        >
          {{ selectedIndustryName || "请选择行业" }}
          <text class="arrow">></text>
        </view>
      </view>

      <!-- 公司性质 -->
      <view class="form-item">
        <view class="form-label">公司性质</view>
        <picker
          mode="selector"
          :range="companyNatureList"
          :value="
            formData.nature
              ? companyNatureList.findIndex(
                  (item) => item.dataKey === formData.nature
                )
              : -1
          "
          range-key="value"
          @change="onNatureChange"
        >
          <view class="picker-value">
            <text class="picker-text">{{ getNatureDisplayText(formData.nature) || "请选择公司性质" }}</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>

      <!-- 人员规模 -->
      <view class="form-item">
        <view class="form-label">人员规模</view>
        <picker
          mode="selector"
          :range="staffSizeList"
          :value="
            formData.peopleSize
              ? staffSizeList.findIndex(
                  (item) => item.dataKey === formData.peopleSize
                )
              : -1
          "
          range-key="value"
          @change="onStaffSizeChange"
        >
          <view class="picker-value">
            <text class="picker-text">{{ getPeopleSizeDisplayText(formData.peopleSize) || "请选择人员规模" }}</text>
            <text class="arrow">></text>
          </view>
        </picker>
      </view>
    </view>

    <!-- 行业选择弹窗 -->
    <view v-if="showIndustryPicker" class="industry-modal">
      <view class="modal-mask" @tap="showIndustryPicker = false"></view>
      <view class="industry-picker-popup">
        <scroll-view class="industry-list" scroll-y>
          <view
            v-for="item in topIndustryList"
            :key="item.id"
            class="industry-item"
          >
            <view class="top-industry">
              <text class="industry-name" style="color: #666">{{
                item.name
              }}</text>
              <view class="industry-actions">
                <text
                  v-if="!item.loaded || item.children.length > 0"
                  class="expand-icon"
                  @tap="toggleIndustry(item)"
                  >{{ item.expanded ? "▼" : "▶" }}</text
                >
              </view>
            </view>

            <view v-if="item.expanded" class="second-industry-list">
              <view
                v-for="child in item.children"
                :key="child.id"
                class="second-industry"
                :class="{ selected: child.selected }"
                @tap="selectIndustry(child)"
              >
                <text class="industry-name">{{ child.name }}</text>
              </view>

              <view
                v-if="item.loaded && item.children.length === 0"
                class="no-data"
              >
                暂无二级行业
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { modifyCompanyInfoApi, getIndustryTopListApi, getChildrenIndustryApi, getStaffSizeDataApi, getCompanyNatureDataApi } from "@/api/company.js";

// 页面参数
const companyId = ref('');

// 表单数据
const formData = ref({
  industry: '',
  nature: '',
  peopleSize: ''
});

// 行业数据
const topIndustryList = ref([]);
const industryCache = ref({}); // 缓存二级行业数据
const selectedIndustryName = ref("");
const showIndustryPicker = ref(false);

// 人员规模数据
const staffSizeList = ref([]);

// 公司性质数据
const companyNatureList = ref([]);

// 页面加载时获取参数
onMounted(async () => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options;
  
  if (options.companyId) {
    companyId.value = options.companyId;
  }
  
  if (options.industry) {
    formData.value.industry = options.industry;
    selectedIndustryName.value = options.industry;
  }
  if (options.nature) {
    formData.value.nature = options.nature;
  }
  if (options.peopleSize) {
    formData.value.peopleSize = options.peopleSize;
  }
  
  try {
    // 加载基础数据
    await Promise.all([
      loadIndustryData(),
      loadNatureData(),
      loadStaffSizeData()
    ]);
  } catch (error) {
    console.error('页面数据加载失败:', error);
  }
});

// 是否可以提交
const canSubmit = computed(() => {
  return formData.value.industry && 
         formData.value.industry.trim() !== '' &&
         formData.value.peopleSize && 
         formData.value.peopleSize.trim() !== '';
  // 公司性质不是必填的
});

// 加载一级行业数据
const loadIndustryData = async () => {
  try {
    const data = await getIndustryTopListApi();
    topIndustryList.value = (data || [])
      .sort((a, b) => (a.sort || 0) - (b.sort || 0))
      .map((item) => ({
        ...item,
        children: [],
        expanded: false,
        loaded: false,
      }));
  } catch (error) {
    uni.showToast({
      title: "加载行业数据失败",
      icon: "none",
    });
  }
};

// 加载二级行业数据
const loadSecondIndustry = async (parentItem) => {
  const topIndustryId = parentItem.id;
  // 检查缓存
  if (industryCache.value[topIndustryId]) {
    parentItem.children = industryCache.value[topIndustryId];
    parentItem.loaded = true;
    return;
  }

  try {
    uni.showLoading({ title: "加载中..." });
    const data = await getChildrenIndustryApi(topIndustryId);
    const secondList = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
    parentItem.children = secondList;
    parentItem.loaded = true;
    industryCache.value[topIndustryId] = secondList;
    uni.hideLoading();
  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: "加载二级行业失败",
      icon: "none",
    });
  }
};

// 加载公司性质数据
const loadNatureData = async () => {
  try {
    const data = await getCompanyNatureDataApi();
    companyNatureList.value = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
  } catch (error) {
    uni.showToast({
      title: "加载公司性质数据失败",
      icon: "none",
    });
  }
};

// 加载人员规模数据
const loadStaffSizeData = async () => {
  try {
    const data = await getStaffSizeDataApi();
    staffSizeList.value = (data || []).sort(
      (a, b) => (a.sort || 0) - (b.sort || 0)
    );
  } catch (error) {
    uni.showToast({
      title: "加载人员规模数据失败",
      icon: "none",
    });
  }
};

// 事件处理函数
const toggleIndustry = async (item) => {
  item.expanded = !item.expanded;

  if (item.expanded && !item.loaded) {
    await loadSecondIndustry(item);
  }
};

const selectIndustry = (industry) => {
  formData.value.industry = industry.name;
  selectedIndustryName.value = industry.name;
  showIndustryPicker.value = false;

  // 重置所有选中状态
  topIndustryList.value.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => (child.selected = false));
    }
  });

  industry.selected = true;
};

// 公司性质选择
const onNatureChange = (e) => {
  const index = parseInt(e.detail.value);
  if (index >= 0 && companyNatureList.value[index]) {
    const nature = companyNatureList.value[index];
    formData.value.nature = nature.dataKey;
  } else {
    formData.value.nature = "";
  }
};

// 人员规模选择
const onStaffSizeChange = (e) => {
  const index = parseInt(e.detail.value);
  if (index >= 0 && staffSizeList.value[index]) {
    const staffSize = staffSizeList.value[index];
    formData.value.peopleSize = staffSize.dataKey;
  } else {
    formData.value.peopleSize = "";
  }
};

// 获取公司性质显示文本
const getNatureDisplayText = (dataKey) => {
  if (!dataKey) return '';
  const item = companyNatureList.value.find(item => item.dataKey === dataKey);
  return item ? item.value : dataKey;
};

// 获取人员规模显示文本
const getPeopleSizeDisplayText = (dataKey) => {
  if (!dataKey) return '';
  const item = staffSizeList.value.find(item => item.dataKey === dataKey);
  return item ? item.value : dataKey;
};

// 提交表单
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    uni.showLoading({
      title: "保存中...",
      mask: true,
    });

    const submitData = {
      companyId: companyId.value,
      industry: formData.value.industry,
      nature: formData.value.nature,
      peopleSize: formData.value.peopleSize
    };

    await modifyCompanyInfoApi(submitData);

    uni.hideLoading();
    uni.showToast({
      title: "保存成功",
      icon: "success",
      duration: 2000
    });

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      // 发送事件通知编辑页面重新获取数据
      uni.$emit('companyInfoUpdated');
      uni.navigateBack();
    }, 1000);

  } catch (error) {
    uni.hideLoading();
    uni.showToast({
      title: error.message || "保存失败",
      icon: "none",
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped>
.page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 30rpx 20rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #eee;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.nav-right {
  width: 120rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-btn {
  font-size: 32rpx;
  color: #007aff;
  font-weight: 500;
  padding: 10rpx 20rpx;
  border-radius: 6rpx;
  background-color: rgba(0, 122, 255, 0.1);
  transition: all 0.3s ease;
}

.save-btn:active {
  background-color: rgba(0, 122, 255, 0.2);
}

.save-btn.disabled {
  color: #c0c0c0;
  background-color: rgba(192, 192, 192, 0.1);
}

.container {
  padding: 20rpx;
}

.form-item {
  display: flex;
  flex-direction: column;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background: #fff;
  width: 100%;
  box-sizing: border-box;
  margin-bottom: 20rpx;
  border-radius: 8rpx;
}

.form-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.form-label {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 20rpx;
}

.picker-value {
  width: 100%;
  font-size: 32rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 48rpx;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1rpx solid #e9ecef;
  box-sizing: border-box;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.picker-text {
  flex: 1;
  margin-right: 20rpx;
  word-wrap: break-word;
  overflow-wrap: break-word;
  max-width: calc(100% - 60rpx);
}

.picker-value .arrow {
  color: #999;
  font-size: 28rpx;
  flex-shrink: 0;
  margin-left: 10rpx;
}

.picker-value.disabled {
  color: #999;
}

/* 行业选择弹窗样式 */
.industry-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 999;
}

.modal-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
}

.industry-picker-popup {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.industry-list {
  max-height: 70vh;
}

.industry-item {
  border-bottom: 1rpx solid #f5f5f5;
}

.top-industry {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background: #fafafa;
}

.industry-name.selected {
  color: #007aff;
  font-weight: bold;
}

.industry-name {
  font-size: 30rpx;
  color: #333;
  flex: 1;
}

.top-industry .industry-name {
  color: #666;
  font-weight: bold;
}

.industry-actions {
  margin-left: 20rpx;
}

.expand-icon {
  color: #999;
  font-size: 24rpx;
}

.second-industry-list {
  background: #fff;
}

.second-industry {
  padding: 25rpx 30rpx 25rpx 60rpx;
  border-bottom: 1rpx solid #f5f5f5;
}

.second-industry:last-child {
  border-bottom: none;
}

.second-industry.selected {
  background: #e6f7ff;
}

.second-industry .industry-name {
  font-size: 28rpx;
  color: #666;
}

.no-data {
  padding: 30rpx 60rpx;
  text-align: center;
  color: #999;
  font-size: 28rpx;
}
</style>
